#include "client.h"
#include "ui_client.h"

Client::Client(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    config=new Config();
    ui->lblError->setStyleSheet("color:red");
    client=new QTcpSocket();
    server=config->getServer();
    port=config->getPort();
}

Client::~Client()
{
    delete ui;
}

void Client::on_pushButton_2_clicked()
{
    close();
}

void Client::on_pushButton_clicked()
{
    if(ui->txtUsername->text()=="")
    {
        ui->lblError->setText("Username must not be null.");
        return;
    }
    if(ui->txtPassword->text()=="")
    {
        ui->lblError->setText("Password must not be null.");
        return;
    }
    try
    {
        client->connectToHost(QHostAddress(server),port);
        if(!client->waitForConnected(5000))
        {
            ui->lblError->setText("Connection Error!");
            return;
        }
        QString str="6001|"+ui->txtUsername->text()+"|"+ui->txtPassword->text();
        //qDebug()<<str;
        QByteArray qb=str.toLatin1();
        char* s=qb.data();
        client->write(s);
        connect(client,SIGNAL(readyRead()),this,SLOT(getData()));
    }
    catch(QException ex)
    {
        ui->lblError->setText(ex.what());
    }
}

void Client::getData()
{
    QByteArray datagram=client->readAll();
    //qDebug()<<datagram.size();
    QString str(datagram);
    //qDebug()<<datagram<<str;
    if(str=="6100")
    {
        QMainWindow* main=new frmMain();
        main->show();
        this->close();
    }
    else if(str!="")
        ui->lblError->setText("ErrorCode:"+str);
    else
        ui->lblError->setText("unknown Error!");
    client->close();
}
